<template>
  <div>
    <div class="clear">
      <Button v-if="isShowBtn" type="primary">
        <router-link :to="{ path: '/login' }" style="color:#fff;">返回登陆页面</router-link>
      </Button>
    </div>
    <Card>
      <Row :gutter="20">
        <Col v-for="(item,index) in questionnaire" :key="index" :xs="24" :md="8" :lg="6">
          <div class="containers clear">
            <h3 class="hidden-font" title="民主测评问卷">{{item.examName}}</h3>
            <p>开始时间：{{item.startDate}}</p>
            <p>结束时间：{{item.endDate}}</p>
            <p class="hidden-font" :title="item.examer">测评对象：{{item.examer}}</p>
            <div
              v-if="Number(item.startDate) <= Number(date) && Number(date) <= Number(item.endDate)"
            >
              <Button
                v-if="btnAccess.add"
                @click="jumpTest(item.examId,item.departCode,item.examer,item.id,item.listExamers)"
                type="primary"
                class="test"
              >在线测评</Button>
            </div>
          </div>
        </Col>
      </Row>
      <Row v-if="spinShow">
        <Col class="demo-spin-col" span="24">
          <Spin fix>
            <Icon type="ios-loading" size="18" class="demo-spin-icon-load"></Icon>
            <div>数据加载中</div>
          </Spin>
        </Col>
      </Row>
    </Card>
    <!-- 非用户登陆需要输入手机号码 -->
    <Modal v-model="isShowModal" title="请输入手机号码" :closable="false" :mask-closable="false">
      <Form ref="formData" :model="formData" :rules="formReg" :label-width="80">
        <Row>
          <Col span="15">
            <FormItem label="联系电话" prop="phone">
              <Input :number="true" v-model="formData.phone" placeholder="请输入联系电话(必填)"></Input>
            </FormItem>
          </Col>
        </Row>
        <div class="redTips">手机号码仅用来确认您的身份,不做其他用途,我们会将您的数据做好保密,请放心填写。</div>
      </Form>
      <div slot="footer">
        <Button size="large" @click="cancelModal('formData')">取消</Button>
        <Button
          type="primary"
          size="large"
          :loading="modalLoading"
          @click="submitModal('formData')"
        >提交</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { questionMangeAjax } from "@/api/measurement";
// 查询
const QUERY_URL = "/examManage/query";
// 手机验证
const PHONE_REG = new RegExp("^1(3|4|5|7|8)\\d{9}$");

export default {
  data() {
    // 验证手机号码
    const phoneReg = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入联系电话"));
      } else if (!PHONE_REG.test(this.formData.phone)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };
    return {
      // 增删改查权限按钮
      btnAccess: {
        add: true,
        add2: "inline-block",
        del: "inline-block",
        upd: true,
        query: true
      },
      userType: 1, // 是否为用户
      isShowBtn: false,
      questionnaire: [],
      spinShow: false,
      // 模态框
      isShowModal: false,
      modalLoading: false,
      formData: {
        phone: ""
      },
      formReg: {
        phone: [
          {
            required: true,
            message: "请输入正确的手机号码",
            validator: phoneReg,
            trigger: "blur"
          }
        ]
      },
      date: 0,
      isHavePhone: "false" // 判断是否有手机号码
    };
  },
  methods: {
    // 查询
    _getMeasurementData(formData, url) {
      this.spinShow = true;
      const keyOne = "filter";
      questionMangeAjax({ formData, url, keyOne })
        .then(result => {
          this.spinShow = false;
          if (result.data.code === "200") {
            let item = result.data.results;
            this.questionnaire = item.list;
            this.userType = item.userType;
            if (item.userType === "0") {
              this.isShowBtn = true;
            }
            this.$Message.success("查询成功");
          } else {
            this.$Message.error("查询失败");
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    /**
     * @method 跳转到测评试卷
     * @param id 试卷标题id
     * @params departCode  单位id
     * @params examer  测评对象
     * @params ids  唯一标识
     * @param listExamers 测评对象数组
     */
    jumpTest(id, departCode, examer, ids, listExamers) {
      this.formData.id = id;
      this.formData.departCode = departCode;
      this.formData.examer = examer;
      this.formData.ids = ids;
      this.formData.listExamers = listExamers;
      let phone = this.formData.phone;

      // 储存手机号码状态
      let isPhone = sessionStorage.getItem("isHavePhone");
      this.isHavePhone = isPhone;
      // 判定是否有填写过手机号码，有的话就不用再次填写
      if (this.isHavePhone === "true") {
        this.$router.push({
          name: "test_page",
          params: {
            id,
            departCode,
            examer,
            phone,
            ids,
            listExamers
          }
        });
        return;
      }

      if (this.userType === "0") {
        this.isShowModal = true;
        return;
      }

      this.$router.push({
        name: "unit_measurements",
        params: {
          id,
          departCode,
          examer,
          ids,
          listExamers
        }
      });
    },
    cancelModal(name) {
      this.isShowModal = false;
      this.$refs[name].resetFields();
    },
    submitModal(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          // 储存是是否有输入电话号码状态 和手机号码
          sessionStorage.setItem("isHavePhone", true);
          sessionStorage.setItem("userPhone", this.formData.phone);

          this.isShowModal = false;
          let id = this.formData.id;
          let departCode = this.formData.departCode;
          let examer = this.formData.examer;
          let phone = this.formData.phone;
          let ids = this.formData.ids;
          let listExamers = this.formData.listExamers;
          this.$router.push({
            name: "test_page",
            params: {
              id,
              departCode,
              examer,
              phone,
              ids,
              listExamers
            }
          });
        } else {
          this.$Message.error("请输入正确的手机号码!");
        }
      });
    }
  },
  created() {
    // 判断是否在测评时间范围内
    let nowDate = new Date();
    let year = nowDate.getFullYear();
    let month =
      nowDate.getMonth() + 1 < 10
        ? "0" + (nowDate.getMonth() + 1)
        : nowDate.getMonth() + 1;
    let day =
      nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
    let dateStr = year + "" + month + "" + day; // 字符串拼接
    this.date = Number(dateStr);
    this._getMeasurementData("", QUERY_URL);
    // 获取按钮权限
    let btnAccess = sessionStorage.getItem("btnaccess");
    this.globalFunction(btnAccess);

    // 获取是否填写过手机号码
    let isPhone = sessionStorage.getItem("isHavePhone");
    this.isHavePhone = isPhone;
  }
};
</script>
<style lang="less" scoped>
.containers {
  height: 180px;
  border: 1px solid #aab2bd;
  border-top: 4px solid #aab2bd;
  border-radius: 5px;
  padding: 7px;
  margin-bottom: 10px;
  h3 {
    margin: 10px 0;
  }
  .test {
    margin: 10px 0;
    float: right;
  }
  p {
    color: #aab2bd;
    width: 100%;
  }

  &:after {
    content: "";
    clear: both;
    display: block;
  }
  &:hover {
    border-top: 4px solid #38b5e8;
  }
}
.test-tag {
  width: 100px;
  height: 40px;
  line-height: 40px;
  background: #009ee7;
  text-align: center;
  color: #fff;
  margin-bottom: 10px;
}
.clear::after {
  content: "";
  clear: both;
  display: block;
}
.clear button {
  float: right;
  margin: 10px;
}

.hidden-font {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
